<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HealthSportController extends ApiController
{

    /**
     * 获取用户运动记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $diary_id = $request->input("id", 0);
        if (empty($diary_id)) {
            return $this->failed("参数错误");
        }
        $health_diary = DB::table('user_health_diary')->select('id', 'sport_caloric', 'date')->where(['id' => $diary_id, 'user_id' => $user_id])->first();
        if(empty($health_diary)) {
            $this->failed("参数错误");
        }

        $sport_record = DB::table('user_health_sport AS s')
            ->leftJoin('sports AS ss', 'ss.id', '=', 's.sport_id')
            ->select('s.id', 's.count', 's.caloric', 'ss.name')
            ->where(['s.diary_id' => $diary_id])
            ->get();
        $sport_record = empty($sport_record) ? [] : $sport_record;
        return $this->success(['health_diary' => $health_diary, 'sport_record' => $sport_record]);
    }

    /**
     * 搜索运动项目
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchSport(Request $request)
    {
        $name = $request->input("name", "");
        $page = $request->input("page", 1);
        $where[] = ['status', '=', 1];
        if (!empty($name)) {
           $where[] = ['name', 'like', "%{$name}%"];
        }
        $limit = 10;
        $count = DB::table('sports')->where($where)->count();
        $sports = DB::table('sports')->select('id', 'name', 'caloric')->where($where)->skip($limit * ($page -1))->take($limit)->get();
        return $this->success(['sports' => $sports, 'more' => $count > $page * $limit ? true : false]);
    }


    /**
     * 添加运动记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addHealthSport(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $sport_id = $request->input('sport_id', 0);
        $diary_id = $request->input("diary_id", 0);
        $count = $request->input('count', 0);

        if ($sport_id <= 0) {
            return $this->failed("参数错误");
        }
        if ($diary_id <=0 ) {
            return $this->failed("参数错误");
        }
        if ($count <= 0) {
            return $this->failed("食物重量应大于0");
        }

        $sport = DB::table('sports')->where(['id' => $sport_id, 'status' => 1])->first();
        if (empty($sport)) {
            return $this->failed("该运动不存在");
        }
        $health_diary = DB::table('user_health_diary')->select('id', 'sport_caloric')->where(['id' => $diary_id, 'user_id' => $user_id])->first();
        if(empty($health_diary)) {
            $this->failed("参数错误");
        }

        $caloric = round($count * $sport->caloric / 60, 2);

        DB::beginTransaction(); //开启事务


        //该运动项目是否已添加过
        $sport_is_add = DB::table('user_health_sport')->where(['diary_id' => $diary_id, 'sport_id' => $sport_id])->first();
        if (!empty($sport_is_add)) {
            $eat_res = DB::table('user_health_sport')->where('id', $sport_is_add->id)->update([
                'count' => $sport_is_add->count + $count,
                'caloric' => $sport_is_add->caloric + $caloric
            ]);
        } else {
            $eat_res = DB::table('user_health_sport')->insert([
                'user_id' => $user_id,
                'sport_id' => $sport_id,
                'diary_id' => $diary_id,
                'count' => $count,
                'caloric' => $caloric,
            ]);
        }


        $diary_res = DB::table('user_health_diary')->where('id', $diary_id)->increment('sport_caloric', $caloric);

        if ($eat_res === false || $diary_res === false) {
            DB::rollBack(); //回滚事务
            return $this->failed("添加失败");
        }
        DB::commit(); //提交事务
        return $this->success("添加成功");
    }

    /**
     * 修改运动数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editHealthSport(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $sport_id = $request->input('sport_id', 0);
        $count = $request->input('count', 0);

        if ($sport_id <= 0) {
            return $this->failed("参数错误");
        }

        if ($count <= 0) {
            return $this->failed("食物重量应大于0");
        }

        $health_sport = DB::table('user_health_sport')->where(['id' => $sport_id, 'user_id' => $user_id])->first();
        if (empty($health_sport)) {
            return $this->failed("该记录不存在");
        }

        $health_diary = DB::table('user_health_diary')->select('id', 'sport_caloric')->where(['id' => $health_sport->diary_id])->first();
        if(empty($health_diary)) {
            $this->failed("参数错误");
        }

        $sport = DB::table('sports')->where(['id' => $health_sport->sport_id, 'status' => 1])->first();
        if (empty($sport)) {
            return $this->failed("该运动已不存在，无法修改");
        }

        $caloric = round($count * $sport->caloric / 60, 2);
        $sport_caloric = $health_diary->sport_caloric + $caloric - $health_sport->caloric;
        if ($sport_caloric <= 0) {
            $sport_caloric = 0;
        }

        DB::beginTransaction(); //开启事务

        $eat_res = DB::table('user_health_sport')->where('id', $sport_id)->update([
            'count' => $count,
            'caloric' => $caloric,

        ]);

        $diary_res = DB::table('user_health_diary')->where('id', $health_sport->diary_id)->update(['sport_caloric' => $sport_caloric]);

        if ($eat_res === false || $diary_res === false) {
            DB::rollBack(); //回滚事务
            return $this->failed("修改失败");
        }
        DB::commit(); //提交事务
        return $this->success("修改成功");
    }

    /**
     * 删除运动记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteHealthSport(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $sport_id = $request->input('sport_id', 0);

        if ($sport_id <= 0) {
            return $this->failed("参数错误");
        }

        $health_sport = DB::table('user_health_sport')->where(['id' => $sport_id, 'user_id' => $user_id])->first();
        if (empty($health_sport)) {
            return $this->failed("该记录不存在");
        }

        $health_diary = DB::table('user_health_diary')->select('id', 'sport_caloric')->where(['id' => $health_sport->diary_id])->first();
        if(empty($health_diary)) {
            $this->failed("参数错误");
        }

        $sport = DB::table('sports')->where(['id' => $health_sport->sport_id, 'status' => 1])->first();
        if (empty($sport)) {
            return $this->failed("该运动已不存在，无法修改");
        }

        $sport_caloric = $health_diary->sport_caloric - $health_sport->caloric;
        if ($sport_caloric <= 0) {
            $sport_caloric = 0;
        }

        DB::beginTransaction(); //开启事务
        $eat_res = DB::table('user_health_sport')->where('id', $sport_id)->delete();
        $diary_res = DB::table('user_health_diary')->where('id', $health_sport->diary_id)->update(['sport_caloric' => $sport_caloric]);

        if (empty($eat_res) || $diary_res === false) {
            DB::rollBack(); //回滚事务
            return $this->failed("删除失败");
        }
        DB::commit(); //提交事务
        return $this->success("删除成功");
    }
}
